package com.shiwaixiangcun.customer.module.housebutler

import android.content.Context
import android.graphics.Rect
import android.os.Bundle
import android.support.constraint.ConstraintLayout
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.BannerBean
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.BannerImageLoader
import com.shiwaixiangcun.customer.module.houserenting.CommonListEntity
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.activity.CommonWebActivity
import com.shiwaixiangcun.customer.ui.activity.LoginActivity
import com.shiwaixiangcun.customer.ui.activity.OnlineServiceActivity
import com.shiwaixiangcun.customer.utils.*
import com.shiwaixiangcun.customer.widget.bannerview.Banner
import kotlinx.android.synthetic.main.activity_house_butler.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * 铂金管家  主页
 */
class HouseButlerMainActivity : BaseActivity(), View.OnClickListener {

    private var state: CollapsingToolbarLayoutState? = null


    private enum class CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    override fun onClick(p0: View?) {
        val bundle = Bundle()
        when (p0?.id) {
            R.id.back_left -> {
                finish()
            }
            R.id.clayout_record -> {
                if (LoginHelper.isLogin(mContext)) {
                    readyGo(ServiceRecordActivity::class.java)
                } else {
                    readyGo(LoginActivity::class.java)
                }
            }


        }
    }

    companion object {
        const val REQUEST_BANNER = 0x0001
        const val REQUEST_DATA = 0x0010
    }


    private var mHeaderView: View? = null
    private var mBanner: Banner? = null
    private var viewBanner: View? = null
    private var bottomView: View? = null
    private var mCategoryList: ArrayList<ButlerCategory>? = null
    private var mAdapterButler: AdapterButler? = null

    private var mCLayoutRecord: ConstraintLayout? = null
    var siteId: Int = 20
    private var pageStart: Int = 1
    var pageSize: Int = 15
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_house_butler)
        EventUtil.getInstance().register(this)
        siteId = AppSharePreferenceMgr.get(mContext, ConfigSps.CURRENT_SITE_ID, 20) as Int
        pageStart = GlobalConfig.first_page
        pageSize = GlobalConfig.page_size
        initHeaderView()
        initViewAndEvent()
        initBanner()
        initData()
    }



    private fun initData() {

//        mSwxc?.getButlerCategory(siteId);
        OkGo.get<String>(GlobalApi.butlerMain)
                .params("siteId", siteId)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        Log.e(BUG_TAG, response?.body().toString())

                        val type = object : TypeToken<CommonListEntity<ButlerCategory>>() {}.type

                        val butlerList = JsonUtil.fromJson<CommonListEntity<ButlerCategory>>(response?.body(), type)
                        when (butlerList.responseCode) {
                            ResponseConfig.SUCCESS -> {

                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.BUTLER_MAIN, REQUEST_DATA, butlerList.data))

                            }
                        }

                    }
                })

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updaeUI(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.BUTLER_MAIN) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_BANNER -> {
                val bannerList = simpleEvent.data as List<BannerBean>

                val imageList = bannerList.map { it.imagePath }.toList()

                if (imageList.isEmpty()) {
                    mBanner?.visibility = View.GONE
                } else {
                    mBanner?.visibility = View.VISIBLE
                    mBanner!!.setImages(imageList)
                            .setImageLoader(BannerImageLoader())
                            .setDelayTime(4000)
                            .start()

                    mBanner?.setOnBannerListener { position ->
                        val bannerBean = bannerList[position]
                        when (bannerBean.bannerType) {
                            "H5" -> {
                                val bundle = Bundle()
                                bundle.putString("h5_url", bannerBean.link as String?)
                                bundle.putString("h5_name", "")
                                if (!bannerBean.link.isNullOrEmpty()) {
                                    readyGo(CommonWebActivity::class.java, bundle)
                                }
                            }
                            else -> {
                                UIClickManager.bannerClick(mContext, bannerBean.link)
                            }

                        }
                    }
                }
            }
            REQUEST_DATA -> {
                val categoryList = simpleEvent.data as List<ButlerCategory>
                mCategoryList?.addAll(categoryList)
                mAdapterButler?.notifyDataSetChanged()
            }
        }
    }

    private fun initViewAndEvent() {
        app_bar.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
            when {
                verticalOffset == 0 -> {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED
                        tv_page_name.text = "铂金管家"
                        tv_page_name.setTextColor(resources.getColor(R.color.ui_white))
                        back_left.setImageResource(R.mipmap.icon_back_lwhite)

                    }
                }
                (Math.abs(verticalOffset) >= appBarLayout.totalScrollRange) -> {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        tv_page_name.text = "铂金管家"
                        tv_page_name.setTextColor(resources.getColor(R.color.black_text_100))
                        back_left.setImageResource(R.mipmap.icon_back_green)
                        state = CollapsingToolbarLayoutState.COLLAPSED
                    }
                }
                else -> {
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
//                        playButton.setVisibility(View.GONE);//由折叠变为中间状态时隐藏播放按钮
                    }
                    state = CollapsingToolbarLayoutState.INTERNEDIATE


                }
            }
        }
        back_left.setOnClickListener { finish() }
        mCategoryList = ArrayList()
        mAdapterButler = AdapterButler(mCategoryList)
        mAdapterButler?.addHeaderView(viewBanner)
        mAdapterButler?.addFooterView(bottomView)
        val gridLayoutManager = GridLayoutManager(mContext, 3)
        rv_butler_category?.layoutManager = gridLayoutManager
        rv_butler_category?.adapter = mAdapterButler
        rv_butler_category?.addItemDecoration(MarginDecoration(mContext))

        mAdapterButler?.setOnItemClickListener { adapter, view, position ->


            if (LoginHelper.isLogin(mContext)) {
                val butlerCategory = mCategoryList!![position]

                val bundle = Bundle()
                bundle.putLong("id", butlerCategory.id)
                bundle.putString("name", butlerCategory.name)
                readyGo(OnlineServiceActivity::class.java, bundle)
            } else {
                readyGo(LoginActivity::class.java)
            }


        }


    }

    override fun onDestroy() {

        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }


    /**
     * 初始化Banner
     */
    private fun initBanner() {
        OkGo.get<String>(GlobalApi.getBanner)
                .params("siteId", siteId)
                .params("position", GlobalConfig.SWSH_HOUSEKEEPER_01)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        Log.e(BUG_TAG, response.toString())
                    }

                    override fun onSuccess(response: Response<String>?) {
                        val jsonString = response?.body()
                        val type = object : TypeToken<ResponseEntity<List<BannerBean>>>() {}.type
                        val responseEntity = JsonUtil.fromJson<ResponseEntity<List<BannerBean>>>(jsonString, type)
                        when (responseEntity.responseCode) {
                            1001 -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.BUTLER_MAIN, REQUEST_BANNER, responseEntity.data))
                            }
                        }

                    }
                })

    }

    private fun initHeaderView() {
        viewBanner = layoutInflater.inflate(R.layout.header_butler_banner, null, false)
        bottomView = layoutInflater.inflate(R.layout.bottom_butler, null, false)
        mBanner = viewBanner?.findViewById(R.id.banner_header)
        mCLayoutRecord = bottomView?.findViewById(R.id.clayout_record)
        mCLayoutRecord?.setOnClickListener(this)

        val widthPx = ScreenUtil.getScreenWidth(this)
        val paddingPx = DisplayUtil.dip2px(this, 40f)

        val bannerHeight = (widthPx - paddingPx) / 3
        val layoutParams = mBanner?.layoutParams
        layoutParams?.height = bannerHeight

        mBanner?.layoutParams = layoutParams

    }

    internal inner class MarginDecoration(context: Context) : RecyclerView.ItemDecoration() {
        private val margin: Int = DisplayUtil.dip2px(context, 5f)

        override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State?) {
            outRect.set(0, 0, 0, 0)
        }
    }
}
